<template>
  <view class="container">
    <custom-navbar :immersive="true" title="会员注册" :showBack="showBack" color="#333"> </custom-navbar>
    <view class="container_header" :style="{ paddingTop: `${navbarHeight}px` }"></view>
    <view class="container_content">
      <view class="container_content_box">
        <view class="container_content_box_pic">
          <!-- <image src="/static/image/register_pic.png" mode="widthFix" /> -->
        </view>
        <view class="container_content_box_row">
          <view class="container_content_box_row_label">会员名称</view>
          <view class="container_content_box_row_input"> <input type="nickname" placeholder="请输入" v-model="form.name" @input="onNicknameInput" /></view>
        </view>
        <view class="container_content_box_row">
          <view class="container_content_box_row_label">联系方式</view>
          <view class="container_content_box_row_input phone">
            <input placeholder="请输入" v-model="form.phone" type="number" maxlength="11" />
            <button class="container_content_box_row_input_btn" type="primary" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">获取手机号</button>
          </view>
        </view>
        <view class="container_content_box_row">
          <view class="container_content_box_row_label">密码</view>
          <view class="container_content_box_row_input"> <input placeholder="请输入" v-model="form.password" password /></view>
        </view>
        <!-- <view class="container_content_box_row">
          <view class="container_content_box_row_label">确认密码</view>
          <view class="container_content_box_row_input"> <input placeholder="请输入" v-model="form.confirmPassword" password /></view>
        </view> -->
        <view class="container_content_box_row">
          <view class="container_content_box_row_label">身份证号码</view>
          <view class="container_content_box_row_input"> <input placeholder="请输入" v-model="form.idcard" /></view>
        </view>
        <view class="container_content_box_row">
          <view class="container_content_box_row_label">区域</view>
          <view class="container_content_box_row_input">
            <picker @change="bindPickerChange" range-key="name" :range="areaList">
              <view class="uni-input">{{ selectName ? selectName : '请选择' }}</view>
            </picker>
          </view>
        </view>
      </view>
    </view>
    <view class="container_bottom">
      <button class="container_bottom_btn" @tap="save">确认加入</button>
    </view>
  </view>
</template>

<script>
import { encrypt } from '@/utils/func.js'
import { appletInviteRegister, getArea } from '@/service/api/register'
import navbarMixin from '@/mxins/navbar.js'
import { setToken, setUserInfo, getCompanyLogo, getPhone } from '@/service/auth.js'

export default {
  name: 'index',
  mixins: [navbarMixin],
  data() {
    return {
      form: {
        wxCode: '',
        name: '',
        phone: '',
      },
      userInfo: {},
      customerAreaList: [],
      logo: '',
      customerArea: {},
      showPop: true,
      mask: true,

      required: [
        {
          prop: 'name',
          name: '会员名称',
        },
        {
          prop: 'phone',
          name: '联系方式',
        },
        {
          prop: 'password',
          name: '密码',
        },
        // {
        //   prop: 'confirmPassword',
        //   name: '确认密码',
        // },
      ],
      userId: '',
      areaList: [],
      selectName: '',
      showBack: false,
      areaId: '',
    }
  },
  checkData(data) {
    for (let i of this.required) {
      if (!data[i.prop]) return uni.showToast({ title: `请检查${data[i.prop]}是否输入` })
    }
    return true
  },
  onLoad(options) {
    //接收扫码所传来的参数
    console.log('option' + JSON.stringify(options))
    if (options.userId) {
      this.userId = options.userId
    } else {
      this.showBack = true
    }

    if (options.areaId) {
      this.areaId = options.areaId
    }

    //扫描二维码
    if (options.scene) {
      // 解码scene参数
      const scene = decodeURIComponent(options.scene)
      console.log('场景值:', scene)

      // 解析参数（假设是key=value格式）
      const params = {}
      scene.split('&').forEach(item => {
        const [key, value] = item.split('=')
        params[key] = value
      })

      this.userId = params.userId
    }

    console.log('二维码传过来的userId', this.userId)
    this.getMyArea()
  },
  created() {},
  mounted() {},
  methods: {
    onNicknameInput(e) {
      this.form.name = e.detail.value
    },
    async getPhoneNumber(e) {
      const that = this
      if (e.detail.errMsg === 'getPhoneNumber:ok') {
        // 获取到加密数据
        const { encryptedData, iv } = e.detail
        console.log('encryptedData',encryptedData)
        const phoneInfo = await getPhone(encryptedData, iv)
        console.log('phone', phoneInfo.phoneNumber)
        that.form.phone = phoneInfo.phoneNumber
      } else {
        // 用户拒绝授权
        uni.showToast({
          title: '获取手机号失败',
          icon: 'none',
        })
      }
    },
    async getWxCode() {
      return new Promise((resolve, reject) => {
        wx.login().then(res => {
          resolve(res.code)
        })
      })
    },
    getMyArea() {
      getArea()
        .then(res => {})
        .catch(err => {
          console.log('res', err)
          if (err.content) {
            this.areaList = err.content.filter(item => item.name !== '默认区域')
            const areaItem = err.content.find(item => item.id === this.areaId)
            if (areaItem) {
              this.form.areaId = areaItem.id
              this.selectName = areaItem.name
            }
          }
        })
    },
    bindPickerChange(data) {
      console.log('data', data)
      const index = data.detail.value
      let item = this.areaList[index]
      this.form.areaId = item.id
      this.selectName = item.name
    },
    async save() {
      const _that = this
      for (let i of _that.required) {
        if (!_that.form[i.prop])
          return uni.showToast({
            title: `请检查${i.name}是否输入`,
            icon: 'none',
          })
      }
      // if (_that.form.password !== _that.form.confirmPassword) {
      //   return uni.showToast({ title: `密码不一致`, icon: 'none' })
      // }
      if (!_that.form.areaId) {
        return uni.showToast({ title: `请先选择区域`, icon: 'none' })
      }

      const encryptPass = encrypt(_that.form.password)
      const encryptConfirmPass = encrypt(_that.form.password)
      const wxCode = await _that.getWxCode()
      _that.form.wxCode = wxCode

      const param = {
        ..._that.form,
        ...{ password: encryptPass, confirmPassword: encryptConfirmPass },
      }
      if (_that.userId) {
        param.referenceId = _that.userId
      }
      console.log('param' + JSON.stringify(param))

      uni.showLoading({ title: '注册中' })
     appletInviteRegister(param)
        .then(res => {
          _that.uniHideLoading()
          const {
            status,
            data: { token, user },
          } = res

          if (status == 200) {
            setToken(token)
            setUserInfo(user)
            uni.switchTab({
              url: '/pages/home/index',
            })
          }
        })
        .catch(err => {
          _that.uniHideLoading()
          _that.uniShowToast(err.msg)
        })
    },

    login_wx() {
      const _this = this
      uni.showModal({
        title: '温馨提示',
        content: '获取你的昵称、头像、地区及性别',
        success(res) {
          //如果用户点击了确定按钮
          if (res.confirm) {
            uni.getUserProfile({
              desc: '获取你的昵称、头像、地区及性别',
              success: res => {
                _this.userInfo = res.userInfo
              },
              fail: res => {
                //拒绝授权
                uni.showToast({
                  title: '您拒绝了请求,不能正常使用小程序',
                  icon: 'error',
                  duration: 2000,
                })
                return
              },
            })
          } else if (res.cancel) {
            //如果用户点击了取消按钮
            uni.showToast({
              title: '您拒绝了请求,不能正常使用小程序',
              icon: 'error',
              duration: 2000,
            })
            return
          }
        },
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.container {
  width: 100vw;
  height: 100vh;
  /* background-image: url('/static/image/register_bg.png');
  background-size: cover;
  background-repeat: no-repeat; */
  display: flex;
  flex-direction: column;
  &_header {
    height: 100rpx;
    line-height: 100rpx;
    text-align: center;
  }
  &_content {
    flex: 1;
    display: flex;
    flex-direction: column;
    &_box {
      flex: 1;
      background-color: white;
      margin: 20rpx;
      border-radius: 10rpx;
      &_pic {
        image {
          width: 100%;
        }
      }
      &_row {
        display: flex;
        justify-content: space-between;
        border-bottom: 1rpx solid #f1f1f1;
        padding: 30rpx 20rpx;
        &_input {
          flex: 1;
          text-align: right;
          &_btn {
            font-size: 26rpx;
            margin: 0;
          }
        }
      }
    }
  }
  &_bottom {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: white;
    border-top-left-radius: 20rpx;
    border-top-right-radius: 20rpx;
    padding: 20rpx 20rpx 50rpx 20rpx;
    &_btn {
      background: linear-gradient(to left, #ff8f00, #ffb300);
      color: white;
    }
  }
}
.phone {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
